﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Liber;
using Liber.WEB;

namespace FlashQ.Main.Trade
{
    public class TradeController : LiberController
    {
        public JsonResult NewOrder() {
            long dvc_id = Request.TryGetLong("dvc_id", -1);

            //TODO:锁定设备

            //TODO:检查所选商品和服务SKU

            //TODO:创建交易和订单

            DyObject trd = new DyObject();
            trd.Set("trade_idstr", IdFactory.NewID().ToString());
            trd.Set("idstr", IdFactory.NewID().ToString());
            trd.Set("amount", 0.01);
            trd.Set("createtime", DateTime.Now);
            trd.Set("dvc_id", "860696040085106");

            //缓存订单相关信息供后面使用
            Cache.Set<DyObject>("OrderInfo", trd["idstr"].ToString(), trd, 5);

            return Json(FnResult<DyObject>.Sucess(trd));
        }


        public JsonResult DoOrder() {
            long ordId = Request.TryGetLong("ord_id", -1);
            short step = Request.TryGetShort("step", 1);

            //TODO:根据订单ID获取设备信息
            string dvc_id = "";
            var ord = Cache.Get<DyObject>("OrderInfo", ordId.ToString());
            if (ord != null) {
                dvc_id = ord["dvc_id"].ToString();
            }
            else {
                dvc_id= Request.TryGet("dvc_id", "860696040085106");
            }

            //TODO:根据设备的产品类型获取命令配置，可能要分阶段拆分指令，前端需配合页面交互逻辑
            DyObject[] step1 = new DyObject[4];
            //开机
            step1[0] = new DyObject().Set("act", "boot")
                                     .Set("args", Request.TryGet("cmd", "CC0001030F000001000000000000000000000000C0"));

            //设置洗衣模式
            step1[1]= new DyObject().Set("act", "option")
                                    .Set("args", Request.TryGet("cmd", "cc 00 01 03 0f 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 c0"));

            //查询舱门状态
            step1[2] = new DyObject().Set("act", "confirm")
                                     .Set("args", Request.TryGet("cmd", "cc 00 01 03 0f 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 c0"));

            //启动洗衣
            step1[3] = new DyObject().Set("act", "start")
                                     .Set("args", Request.TryGet("cmd", "CC0001030F000003000000000000000000000000C2"));
            //TODO:按前端执行阶段分别发送对应阶段的指令

            short msgChannel = Request.TryGetShort("msg_channel", 1);
            short bitEncoding = Request.TryGetShort("bit_encoding", 0);
            short asciiEncoding = Request.TryGetShort("ascii_encoding", 0);
            string cmd = Request.TryGet("cmd", "cc 00 01 03 0f 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 c0");

            string msg = "";
            if (asciiEncoding == 1) {
                //转换为ASCII字符串
                msg = new DyObject().Set("act", "start").Set("args", HexToASCI.ConvertStr(cmd)).FastJson();
            }
            else {
                msg = new DyObject().Set("act", "start").Set("args", cmd).FastJson();
            }

            if (bitEncoding == 1) {
                //转换为二进制字符串
                byte[] data = Encoding.Unicode.GetBytes(msg);
                StringBuilder msgRaw = new StringBuilder(data.Length * 8);
                foreach (byte b in data) {
                    msgRaw.Append(Convert.ToString(b, 2).PadLeft(8, '0'));
                }
                msg = msgRaw.ToString();
            }

            //使用普通Pub接口或RRPC接口
            string rtn = msgChannel == 0 ? IotHelper.SVC.SendCMDSync("washer", dvc_id, msg) : IotHelper.SVC.SendCMD("washer", dvc_id, msg);
            return Json(FnResult.Sucess(null));

            //decimal amount = Request.TryGetDecimal("amount", 0M);
            //string way = Request.TryGet("way", ""); //支付方式
            //string os = Request.TryGet("os", "");   //手机系统类型
            //long orderid = Request.TryGetLong("order_id", -1);  //支付目标订单ID

            //FnResult<DyObject> rtn = null;
            //if (way == "Wallet")
            //{
            //    /*钱包余额支付*/
            //    rtn = API.Request(UID, UNAME, "DemoApp@NewPay")
            //             .Set("payfor", "Order")
            //             .Set("toobj", orderid)
            //             .Set("amount", amount)
            //             .Set("paychannel", "Wallet")
            //             .WaitResult();
            //}
            //else
            //{
            //    /*第三方支付*/
            //    rtn = API.Request(UID, UNAME, "DemoApp@NewPay")
            //             .Set("payfor", "Order")
            //             .Set("toobj", orderid)
            //             .Set("amount", amount)
            //             .Set("paychannel", "FZF-" + way)
            //             .WaitResult();
            //}

            //if (rtn.IsPositive)
            //{
            //    if (way == "Wallet")
            //    {
            //        /*执行钱包扣款并更新支付单状态*/
            //        var pRtn= API.Request(UID,UNAME,"DemoApp@PayEnd")
            //                   .Set("payid", (long)rtn.Data["id"])
            //                   .Set("payfor", "Order")
            //                   .Set("payobj", orderid)
            //                   .Set("receive", amount)
            //                   .Set("deduct",true)
            //                   .WaitResult();
            //        FnResult<DyObject> msg = null;
            //        if (pRtn.IsPositive)
            //        {
            //            msg = FnResult<DyObject>.Sucess(new DyObject().Set("BizType", "OrderPayed")
            //                                                              .Set("OrderIdStr", orderid.ToString())
            //                                                              .Set("Amount", amount));

            //        }
            //        else
            //        {
            //            msg = FnResult<DyObject>.Sucess(new DyObject().Set("BizType", "OrderPayFail")
            //                                                          .Set("OrderIdStr", orderid.ToString()));
            //        }
            //        IM.SendMsg(SessionID, msg.FastJson());
            //    }
            //    else
            //    {
            //        /*第三方支付，等待支付通道处理结果*/
            //        long payId = (long)rtn.Data["id"];
            //        rtn.Data.Set("app_clientid", SessionID);

            //        Cache.Set<DyObject>("OnPaying", payId.ToString(), rtn.Data, 5);
            //        string toPayApp = FzfPay.Pay(os == "A" ? "ANDROID" : "IOS", way, payId, amount, "闪Q空间-订单支付");
            //        if (toPayApp.IsNull())
            //        {
            //            return Json(FnResult<DyObject>.Failure("System", "PayChannelFail"));
            //        }
            //        else
            //        {
            //            rtn.Data.Set("PayData", toPayApp);
            //            return Json(rtn);
            //        }
            //    }
            //}
            //return Json(rtn); 
        }
    }
}